<template>
<!--  地图类型：
  <el-select v-model="BMapSetting.type" @change="selectLineByInitMap" placeholder="请选择">
    <el-option value="BMAP_SATELLITE_MAP" label="卫星图"></el-option>
    <el-option value="BMAP_NORMAL_MAP" label="常规地图"></el-option>
  </el-select>
  <br />
  <br />-->
  <!--项目详情-->
  <el-card v-show="dataMap.showProject" class="box-card" style="z-index: 99;position: absolute;right: 2%;width: 360px">
    <div slot="header" class="clearfix">
      <div style="height:30px;text-align: center;">
        <span style="font-size: 18px">{{ dataMap.projectData.name }}</span>
        <span>
          <i class="el-icon" style="float: right; padding: 3px 0" @click="showProjectTable">
            <svg aria-hidden="true" class="iconfont" style="">
              <use v-if="dataMap.showProjectTable" xlink:href="#icon-caret-down"></use>
              <use v-else xlink:href="#icon-caret-up"></use>
            </svg>
          </i>
        </span>
      </div>
    </div>
    <div v-show="dataMap.showProjectTable">
      <el-descriptions :column="1" :colon="false" :font-family="'Arial'">
        <el-descriptions-item label="  项目位置：">
          <span> {{ dataMap.projectData.provinceName }}</span>
          -<span>{{ dataMap.projectData.cityName }}</span>
          -<span> {{ dataMap.projectData.creaName }}</span>

        </el-descriptions-item>
        <el-descriptions-item label="项目负责人：">{{ dataMap.projectData.projectHead }}</el-descriptions-item>
        <el-descriptions-item label="  项目成员：">{{ dataMap.projectData.projectMember }}人</el-descriptions-item>
        <el-descriptions-item label="  项目状态：">
          <span v-if="dataMap.projectData.state == 0" size="small" type="success">施工中</span>
          <span v-if="dataMap.projectData.state == 1" size="small" type="success">待验收</span>
          <span v-if="dataMap.projectData.state == 2" size="small" type="success">验收通过</span>
        </el-descriptions-item>
        <el-descriptions-item label="  选择路线：">
          <el-select v-model="dataMap.lineId" @change="selectLineByInitMap" multiple filterable placeholder="请选择线路">
            <el-option v-for="item in dataMap.lineOp" :value="item.id" :label="item.name" :key="item.id"></el-option>
          </el-select>
        </el-descriptions-item>
        <el-descriptions-item label="    项目定位点：">{{ dataMap.projectData.equipmentCount }}</el-descriptions-item>
      </el-descriptions>
      <div>
        <el-row :gutter="20" style="max-height: 220px; overflow-y:scroll ">
          <el-col :span="8" v-for="item in dataMap.equipmentCountData" style="padding: 10px">
            <div class="box-cards" style="width: 100%;height: 90px;">
              <div style="font-size: 20px;padding-top: 15px;width: 100%">
                <el-image class="imgs" :src="item.equipmentTypeUrl"></el-image><!-- -->
                <div class="imgs_div">{{ item.equipmentTypeNumber }}</div><!--{{  }}-->
              </div>
              <div>
                <div class="putStyle">{{ item.equipmentName }}</div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
      <div>
        <el-row :gutter="20">
          <el-col :span="12" style="padding: 10px" @click="exportLineId">
            <el-button type="primary">导出当前线路数据</el-button>
          </el-col>
          <el-col :span="12" style="padding: 10px" @click="exportLineIds">
            <el-button type="primary">导出竣工报告</el-button>
          </el-col>
        </el-row>
      </div>
    </div>
  </el-card>
  <!--!线路详情-->
  <el-card v-show="dataMap.showLine" class="box-card" style="z-index: 99;position: absolute;right: 2%;width: 360px">
    <div slot="header" class="clearfix">
      <div style="height:30px;text-align: center;">
        <span style="font-size: 18px">{{ dataMap.lineData.name }}</span>
        <span>
          <i class="el-icon" style="float: right; padding: 3px 0" @click="showLineTable">
            <svg aria-hidden="true" class="iconfont" style="">
              <use v-if="dataMap.showLineTable" xlink:href="#icon-caret-down"></use>
              <use v-else xlink:href="#icon-caret-up"></use>
            </svg>
          </i>
        </span>
      </div>
    </div>
    <div v-show="dataMap.showLineTable">
      <el-descriptions :column="1" :colon="false" :font-family="'Arial'">
        <el-descriptions-item label="  线路名称：">
          {{ dataMap.lineData.name }}
        </el-descriptions-item>
        <el-descriptions-item label="施工日期：">{{ dataMap.lineData.startDate }}</el-descriptions-item>
        <el-descriptions-item label="    定点数：">{{ dataMap.lineData.equipmentCount }}</el-descriptions-item>
      </el-descriptions>
      <div>
        <el-row :gutter="20" style="max-height: 220px; overflow-y:scroll ">
          <el-col :span="8" v-for="item in dataMap.equipmentLineCountData" style="padding: 10px">
            <div class="box-cards" style="width: 100%;height: 90px;">
              <div style="font-size: 20px;padding-top: 15px;width: 100%">
                <el-image class="imgs" :src="item.equipmentTypeUrl"></el-image><!-- -->
                <div class="imgs_div">{{ item.equipmentTypeNumber }}</div><!--{{  }}-->
              </div>
              <div>
                <div class="putStyle">{{ item.equipmentName }}</div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
      <div>
        <el-row :gutter="20"></el-row>
        <el-col :span="8" style="padding: 10px" @click="showProject">
          <el-button type="primary">查看项目详情</el-button>
        </el-col>
      </div>
    </div>
  </el-card>
  <!--!设备详情-->
  <el-card v-show="dataMap.showEquipment" class="box-card"
    style="z-index: 99;position: absolute;right: 2%;width: 360px">
    <div slot="header" class="clearfix">
      <div style="height:30px;text-align: center;">
        <span style="font-size: 18px">{{ dataMap.equipmentBMapClickData.name }}</span>
        <span>
          <i class="el-icon" style="float: right; padding: 3px 0" @click="showEquipmentTable">
            <svg aria-hidden="true" class="iconfont" style="">
              <use v-if="dataMap.showEquipmentTable" xlink:href="#icon-caret-down"></use>
              <use v-else xlink:href="#icon-caret-up"></use>
            </svg>
          </i>
        </span>
      </div>
    </div>
    <div v-show="dataMap.showEquipmentTable">
      <el-descriptions :column="1" :colon="false" :font-family="'Arial'">
        <el-descriptions-item label="  设备名称：">
          {{ dataMap.equipmentBMapClickData.equipmentName }}
        </el-descriptions-item>
        <el-descriptions-item label="施工坐标：">{{ dataMap.projectData.projectHead }}</el-descriptions-item>
        <el-descriptions-item label="  电缆敷设方式：">
          <div v-for="item in dataForm.roughInTypeList">
            <span v-if="dataMap.equipmentBMapClickData.roughInType == '' + item.dictValue" size="small"
              type="success">{{ item.dictLabel }}</span>
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="备注：">{{ dataMap.equipmentBMapClickData.notes }}</el-descriptions-item>
        <el-descriptions-item label="  图片：">
          <el-row :gutter="20">
            <el-col :span="8" v-for="item in dataMap.equipmentBMapClickData.list" style="padding: 10px">
              <el-image style="height: 80px;width: 80px;margin-top: 3px" :src="dataMap.fileUrl + '?name=' + item.url"
                @click="maxImg(dataMap.fileUrl + '?name=' + item.url)"></el-image>
            </el-col>
          </el-row>
        </el-descriptions-item>
        <el-descriptions-item label="图片备注：">{{ dataMap.equipmentBMapClickData.notesImg }}</el-descriptions-item>
      </el-descriptions>
      <div>
        <el-row :gutter="20"></el-row>
        <el-col :span="8" style="padding: 10px" @click="showProject">
          <el-button type="primary">查看项目详情</el-button>
        </el-col>
      </div>
    </div>
  </el-card>
  <div id="mapDivAdd" style="width:100%;height:820px;">
    <div id="mapDiv" style=" width:100%;height:100%; z-index:0;"></div>
  </div>
  <!-- 放大图片的对话框 -->
  <el-dialog v-model="dataMap.dialogVisible">
    <img width="100%" :src="dataMap.currentImage" alt="">
  </el-dialog>
  <!-- 线路导出对话框 -->
  <el-dialog v-model="exportLineMapVisible" width="600px" title="线路导出">
    <div class="export-map" style="width:100%;height:400px;border: 2px solid #5dcabf;border-radius: 2px;">
      <div id="cloneMapDivAdd" style="width:100%;height:100%;">
        <div id="cloneMapDiv" style="width: 100%; height: 100%; z-index: 0; position: relative;"></div>
      </div>
    </div>
    <div class="tip" style="margin-top: 10px;">框内为导出地图图片，可放大缩小手动调节导出</div>
    <template v-slot:footer>
      <el-button @click="exportLineMapVisible = false">取消</el-button>
      <el-button type="primary" @click="exportLineMap()">
        <el-icon v-if="exportLineMapLoading">
          <Loading />
        </el-icon>
        确定
      </el-button>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { reactive, ref, onMounted, watch, nextTick } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
import baseService from "@/service/baseService";
import { useRoute } from "vue-router";
import app from "@/constants/app";
import { getToken } from "@/utils/cache";
import html2canvas from 'html2canvas';
import axios from 'axios';
import domtoimage from "dom-to-image"

const exportLineMapVisible = ref<boolean>(false);
let dataMap = reactive({
  dialogVisible: false,
  currentImage: "" as string,
  showProject: true,
  showProjectTable: true,
  showLine: false,
  showEquipment: false,
  showLineTable: false,
  showEquipmentTable: false,
  projectData: {
    id: '',
    name: '',
    provinceName: '',
    provinceId: '',
    cityName: '',
    cityId: '',
    creaName: '',
    creaId: '',
    projectHead: '',
    projectMember: '',
    createDate: '',
    state: '',
    notes: '',
    equipmentCount: 0
  } as any,
  lineSelect: [] as any,
  equipmentCountData: [] as any,
  equipmentLineCountData: [] as any,
  equipmentDatAll: [] as any,
  line: "",
  lineOp: [] as any,
  lineId: [] as any,
  lineSelectMap: {} as any,
  lineData: {} as any,
  equipmentBMapClickId: "",
  equipmentBMapClickData: {} as any,
  fileUrl: `${app.api}/sys/oss/downloadLocal`
})
let markers = reactive([])
let polylinesList = reactive([])
let BMapSetting = reactive({
  lat: "116.404",
  lng: "39.915",
  type: "BMAP_SATELLITE_MAP",
})

const route = useRoute();
const routeParams = ref({} as any);
routeParams.value = route.params;
dataMap.projectData = routeParams.value;

watch(() => route.params ? route.params : undefined, (newId?: {}) => {
  console.log("开始监视路由变化")
  if (Object.keys(newId as any).length !== 0) {
    routeParams.value = newId;
    dataMap.projectData = newId;
    initLineList();
    setTimeout(() => {
      startSelectLine();
      selectLineByInitMap()
    }, 1000);

  }
})
const dataForm = reactive({
  roughInTypeList: [],
})
onMounted(() => {
  initLineList();
  setTimeout(() => {
    startSelectLine();
    setTimeout(() => {
      selectLineByInitMap()
    }, 300)
  }, 1000);
  baseService.post("/sys/dict/type/getDataAllByType", { "dictType": "fsfx" }).then((res) => {
    Object.assign(dataForm.roughInTypeList, res.data);
  });
})
const maxImg = (url?: string) => {

  dataMap.dialogVisible = true;
  dataMap.currentImage = url as string
}
const initLineList = () => {
  //开始初始化 设备数量
  baseService.get("/sysproject/equipment/findEquipmentCount/", { "projectId": routeParams.value.id }).then((res) => {
    dataMap.projectData.equipmentCount = res.data
  });
  baseService.get("/sysproject/equipment/findEquipmentByLineList/", { "projectId": routeParams.value.id }).then((res) => {
    console.log(res.data)
    dataMap.equipmentCountData = res.data.equipmentCountData
    dataMap.equipmentDatAll = res.data.equipmentData
  });
}
const startSelectLine = () => {
  //初始化线路下拉框
  baseService.get("/sysproject/line/findLineSelect/", { "proId": routeParams.value.id }).then((res) => {
    dataMap.lineOp = res.data
    dataMap.lineId = [];
    //初始化多条线路
    /*dataMap.lineOp.forEach((item: {}) => {
       dataMap.lineId.push(item.id)
     })*/
  });
}

const cloneMap = ref<any>()
const exportLineId = () => {
  if (null == dataMap.lineId || "" == dataMap.lineId || undefined == dataMap.lineId) {
    ElMessage.error({
      message: '请选择您要导出的线路数据',
      duration: 1000,
      onClose: () => {
      }
    });
    return
  } else {
    exportLineMapVisible.value = true
    nextTick(async () => {
      cloneMap.value = await initMap('cloneMapDivAdd', 'cloneMapDiv')
    })
  }
}
const exportLineMapLoading = ref(false)
const exportLineMap = async () => {
  if (exportLineMapLoading.value) return
  exportLineMapLoading.value = true
  const cloneMapDiv = document.getElementById("cloneMapDivAdd");
  if (!cloneMapDiv) return
  const zoom = cloneMap.value.getZoom()
  const image = await domtoimage.toPng(cloneMapDiv,{
    quality:0.5
  })
  // 创建一个 Blob 对象
  const blob = await (await fetch(image)).blob();
  // 创建 FormData 并添加 Blob
  const formData = new FormData();
  formData.append('file', blob, 'screenshot.png');
  const url = `${app.api}/sys/oss/uploadByLocal?token=${getToken()}`;
  // 上传图片
  const response = await axios.post(url, formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  });
  const data = response.data.data;
  let fileName = "";

  //初始化线路下拉框
  let lineIds = dataMap.lineId.join(",");
  baseService.get("/sysproject/line/exportByLineId/", { "lineIds": lineIds, zoom, fileName: data.url }).then((res) => {
    fileName = res.data.fileName;
    onclickExcel(dataMap.fileUrl + '?name=' + fileName, "线路导出.docx").then(() => {
      ElMessage.success('导出成功')
      exportLineMapVisible.value = false
    }).finally(() => {
      exportLineMapLoading.value = false
    })
  }).catch(() => {
    ElMessage.error('导出失败')
  }).finally(() => {
  })
}


const exportLineIds = () => {
  onclickExcel(dataMap.fileUrl + '?name=' + "20240729.docx", "竣工检验意见书.docx")
}

const onclickExcel = (url: string, fileName: string) => {
  return getBlob(url).then(blob => {
    let a = document.createElement('a');
    let url = window.URL.createObjectURL(blob); // 文件下载地址
    a.setAttribute('href', url); // 修改文件名
    a.setAttribute('download', fileName);
    document.body.appendChild(a);
    a.click();
    a.remove();
    window.URL.revokeObjectURL(url); // 释放URL对象
  });
}
const getBlob = (url: string) => {
  return new Promise(resolve => {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = 'blob';
    xhr.onload = () => {
      if (xhr.status === 200) {
        resolve(xhr.response); // 文件作为Blob对象返回
      }
    };
    xhr.send();
  });
}

const showProject = () => {
  dataMap.showEquipment = false;
  dataMap.showEquipmentTable = false;
  dataMap.showProject = true;
  dataMap.showProjectTable = true;
  dataMap.showLine = false;
  dataMap.showLineTable = false;
}
const showEquipmentTable = () => {
  if (dataMap.showEquipmentTable) {
    dataMap.showEquipmentTable = false;
  } else {
    dataMap.showEquipmentTable = true;
  }
}
const showProjectTable = () => {
  if (dataMap.showProjectTable) {
    dataMap.showProjectTable = false;
  } else {
    dataMap.showProjectTable = true;
  }
}
const showLineTable = () => {
  if (dataMap.showLineTable) {
    dataMap.showLineTable = false;
  } else {
    dataMap.showLineTable = true;
  }
}
const lineMapClick = (val: string) => {

  baseService.get("/sysproject/line/" + val).then((res) => {
    console.log("获取线路");
    console.log(res.data);
    Object.assign(dataMap.lineData, res.data);
  });
  //统计所有的坐标点数量
  baseService.get("/sysproject/equipment/findEquipmentCount/",
    { "projectId": routeParams.value.id, "lineId": val }).then((res) => {
      dataMap.lineData.equipmentCount = res.data
    });
  //统计所有的坐标点分组
  baseService.get("/sysproject/equipment/findEquipmentByLineList/",
    { "projectId": routeParams.value.id, "lineId": val }).then((res) => {
      console.log(res.data)
      dataMap.equipmentLineCountData = res.data.equipmentCountData
    });
};
//选择线路后初始化地图
const selectLineByInitMap = () => {

  let marker = {
    icon: "http://api.map.baidu.com/images/blank.gif",
    iconW: 40,
    iconH: 40,
    pointLat: 116.404,
    pointLng: 39.925
  }
  if (null != dataMap.equipmentDatAll) {
    markers = [] as any;
    polylinesList = [] as any;

    dataMap.lineId.forEach((item: {}) => {
      let polyline = { "id": "", list: [] as any } as any;
      dataMap.equipmentDatAll.forEach((eqitem: {}) => {
        let eqitems = eqitem as any;
        if (item == eqitems.lineId) {
          let markerCopy = {} as any;
          Object.assign(marker, markerCopy);
          markerCopy.pointLat = eqitems.lgt;
          markerCopy.pointLng = eqitems.lng;
          markerCopy.id = eqitems.id;
          markerCopy.url = eqitems.equipmentTypeUrl
          markerCopy.name = eqitems.name
          if ("" != markerCopy.url || undefined != markerCopy.url || null != markerCopy.url) {
            markerCopy.url = markerCopy.url.replace("downloadLocal", "downloadLocalByHalf")
          }
          markers.push(markerCopy);
          polyline.list.push(markerCopy)
        }
      })
      polyline.id = item;
      polylinesList.push(polyline)
    })

    if (markers.length > 0) {
      let markersArray = markers[0] as any;
      BMapSetting.lat = markersArray.pointLat
      BMapSetting.lng = markersArray.pointLng
    } else {
      BMapSetting.lat = "116.404";
      BMapSetting.lng = "39.915";
    }
    initMap();
  }
}

const equipmentBMapClick = () => {
  dataMap.equipmentBMapClickData = {};
  dataMap.equipmentDatAll.forEach((item: {}) => {
    let items = item as any;
    if (items.id == dataMap.equipmentBMapClickId) {
      dataMap.equipmentBMapClickData = items
    }
  })
}

let zoom = ref(12) //层级
//初始化地图
const initMap = (mapDivAddId = "mapDivAdd", mapDivId = "mapDiv"): Promise<any> => {
  return new Promise((resolve, reject) => {
    //先删除 dom
    const mapDivAdd: HTMLElement | null = document.getElementById(mapDivAddId);
    const childDiv: HTMLElement | null = document.getElementById(mapDivId);
    const newChildDiv: HTMLDivElement | null = document.createElement("div");
    if (!mapDivAdd || !childDiv || !newChildDiv) return
    if (childDiv) { mapDivAdd.removeChild(childDiv) };
    newChildDiv.id = mapDivId;
    newChildDiv.style = "width:100%;height:100%; z-index:0;"
    newChildDiv.ref = "mapContainer";
    mapDivAdd.append(newChildDiv);
    setTimeout(() => {
      let T = window.T; //这里T指向天地图对象
      let mapTypeOP = [
        { id: "11", name: "普通街道视图", value: window.TMAP_NORMAL_MAP },
        { id: "22", name: "卫星视图", value: window.TMAP_SATELLITE_MAP },
        { id: "33", name: "卫星和路网的混合视图", value: window.TMAP_HYBRID_MAP },
        { id: "44", name: "地形视图", value: window.TMAP_TERRAIN_MAP },
        { id: "55", name: "地形和路网的混合视图", value: window.TMAP_TERRAIN_HYBRID_MAP },
      ]
      BMapSetting.mapTypeOP = mapTypeOP;
      if (T) {
        const map = new T.Map(mapDivId, {
          dragRotate: true,
          dragPan: true,
          WebGLParams: {
            preserveDrawingBuffer: true
          }
        });
        map.setMapType(window.TMAP_SATELLITE_MAP);
        if (markers.length > 0) {
          for (let i = 0; i < markers.length; i++) {
            let markerObj = markers[i];
            let point = new T.LngLat(markerObj.pointLat, markerObj.pointLng)
            let myIcon = new T.Icon({
              "iconUrl": markerObj.url,
              iconSize: new T.Point(30, 30),
              iconAnchor: new T.Point(15, 25)
            });
            let marker;
            if (undefined == markerObj.url || null == markerObj.url || "" == markerObj.url) {
              marker = new T.Marker(point);
            } else {
              marker = new T.Marker(point, { icon: myIcon });
            }

            marker.addEventListener("click", ({ LatLng }: any) => {
              //标点点击
              dataMap.showEquipment = true;
              dataMap.showEquipmentTable = true;
              dataMap.showProject = false;
              dataMap.showProjectTable = false;
              dataMap.showLine = false;
              dataMap.showLineTable = false;
              dataMap.equipmentBMapClickId = markerObj.id;
              equipmentBMapClick();
            })
            map.addOverLay(marker);
            let opts = {
              text: markerObj.name,
              position: new T.LngLat(markerObj.pointLat, markerObj.pointLng), // 指定文本标注所在的地理位置
              offset: new T.Point(2, -2) // 设置文本偏移量
            };
            // 创建文本标注对象
            let label = new T.Label(opts);
            label.setBackgroundColor('white')
            label.setBorderColor('transparent')
            map.addOverLay(label);
          }
        }

        if (polylinesList.length > 0) {
          polylinesList.forEach((item: {}) => {
            let point;
            let points: any[] = [];
            item.list.forEach((item: {}) => {
              let point = new T.LngLat(item.pointLat, item.pointLng)
              points.push(point)
            })
            var polygon = new T.Polyline(points);
            polygon.setColor("red")
            polygon.addEventListener('click', () => {
              dataMap.showEquipment = false;
              dataMap.showEquipmentTable = false;
              dataMap.showProject = false;
              dataMap.showProjectTable = false;
              dataMap.showLine = true;
              dataMap.showLineTable = true;
              lineMapClick(item.id);
            });
            // 将线添加到地图中
            map.addOverLay(polygon);
          })

        }
        map.centerAndZoom(new T.LngLat(BMapSetting.lat, BMapSetting.lng), zoom.value); // 设置中心点和缩放等级
        return resolve(map)

      }
    }, 500)
  })
}
</script>

<style>
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both
}

.box-card {
  width: 480px;
}

.box-cards {
  border-radius: 2px;
  background-color: white;
  border: 1px solid #f1f1f1;
  /* 添加边框 */
  box-shadow: 5px 5px 10px #E5EAF3FF;
  /* 添加阴影 */
  font-size: 16px;
}

.putStyle {
  margin: 0px auto;
  margin-top: 2px;
  width: 70%;
  text-align: center;
  height: 40px;
  font-size: 14px;
  overflow: hidden;
  /* 确保超出的内容会被隐藏 */
  display: -webkit-box;
  /* 使用弹性盒子布局模型 */
  -webkit-line-clamp: 2;
  /* 限制在3行 */
  -webkit-box-orient: vertical;
  /* 垂直排列盒子 */
  text-overflow: ellipsis;
  /* 多行时显示省略号 */
  white-space: normal;
  /* 使用正常的白空格处理方式，必须的 */
}

.imgs {
  height: 22px;
  width: 22px;
  margin-left: 14px;
}

.imgs_div {
  float: right;
  width: 47px;
  text-align: left;
}
</style>
<style scoped>
:deep(.tdt-control-copyright.tdt-control) {
  display: none;
}
</style>
